<template>
  <Select
    v-model:value="state.value"
    show-search
    placeholder="Select users"
    style="width: 100%"
    :filter-option="false"
    :not-found-content="state.fetching ? undefined : null"
    :options="state.data"
    @search="fetchUser"
    @focus="fetchUser"
  >
    <template v-if="state.fetching" #notFoundContent>
      <Spin size="small" />
    </template>
  </Select>
</template>

<script lang="ts" setup>
  import { reactive, defineProps, watch, onMounted } from "vue";
  import { debounce } from "lodash-es";
  import { Select, Spin } from "ant-design-vue";
  import { getPageList } from "#/api";

  const props = defineProps({
    className: {
      type: String,
      required: true,
    },
  });

  let lastFetchId = 0;
  const state = reactive({
    data: [] as { value: string; label: string }[], // 搜索结果列表
    value: "", // 只存 `pid`
    fetching: false, // 加载状态
  });

  // 监听 value 变化
  watch(
    () => state.value,
    (newVal) => {
      console.log("选中的 PID:", newVal);
    }
  );

  // 防抖的搜索函数
  const fetchUser = debounce(async (value: string) => {
    let param: Record<string, any> = {};

    if (typeof value === "object") {
      if (state.data.length > 0) return;
      param = {
        typeName: props.className,
        pageIndex: 0,
        pageSize: 100,
      };
    } else {
      param = {
        typeName: props.className,
        searchKey: value,
        pageIndex: 0,
        pageSize: 100,
      };
    }

    lastFetchId += 1;
    const fetchId = lastFetchId; // 当前请求的唯一 ID
    state.data = [];
    state.fetching = true;

    try {
      const res = await getPageList(param);
      if (fetchId !== lastFetchId) return; // 如果此请求不是最新的，则忽略结果

      state.data = res.records.map((item: any) => ({
        value: item.attrList.find((attr) => attr.attrName === "pid")?.value || "",
        label: item.attrList.find((attr) => attr.attrName === "name")?.displayName || "",
      }));

      // **回填逻辑**
      if (state.value && state.data.length > 0) {
        const matchedOption = state.data.find((opt) => opt.value === state.value);
        if (!matchedOption) {
          state.value = ""; // 选中的值如果不在 options 里，则清空
        }
      }
    } finally {
      state.fetching = false;
    }
  }, 300);

  // 组件挂载时自动获取数据
  onMounted(() => {
    fetchUser("");
  });
</script>
